﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Text;

public partial class ContentView : System.Web.UI.Page
{
    private SqlDataSource dataSource = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            string selectCommand = "SELECT * FROM [DeepZoomList] WHERE UID = '" + Request.QueryString["UID"] + "'";

            dataSource = new SqlDataSource
                (
                    ConfigurationManager.ConnectionStrings["SmartMosaicConnectionString"].ConnectionString,
                    selectCommand
                );

            DeepZoomView.DataSource = dataSource;
            DeepZoomView.DataBind();

            string sql = "SELECT * FROM [DeepZoomList] WHERE UID = @UID";
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SmartMosaicConnectionString"].ConnectionString);
            SqlCommand cmd = new SqlCommand(sql, con);
            cmd.Parameters.AddWithValue("@UID", Request.QueryString["UID"]);
            con.Open();
            SqlDataReader rd = cmd.ExecuteReader();

            if (rd.Read())
            {
                lblContent.Text = rd["Content"].ToString().Replace("\r\n", "<br>");
                lblTitle.Text = rd["Subject"].ToString();
                lblHit.Text = rd["Hit"].ToString();
                lblName.Text = rd["WriterId"].ToString();
                lblDate_time.Text = rd["WriteTime"].ToString();
            }

            rd.Close();
            con.Close();
        }
        ListBind();
    }
    void UpdateReadCount()
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SmartMosaicConnectionString"].ConnectionString);
        string sql = "Update DeepZoomList Set Hit = Hit+1 where UID=@UID";
        SqlCommand cmd = new SqlCommand(sql, con);
        cmd.Parameters.AddWithValue("@UID", Request.QueryString["UID"]);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }

    bool IsWriter(string UID, string userid)
    {
        string sql = "Select Count(*) From DeepZoomList Where UID= @UID And WriterId = @WriterId";
        SqlCommand cmd = new SqlCommand(sql, new SqlConnection(ConfigurationManager.ConnectionStrings["SmartMosaicConnectionString"].ConnectionString));

        cmd.Parameters.AddWithValue("@UID", UID);
        cmd.Parameters.AddWithValue("@WriterId", userid);

        cmd.Connection.Open();
        int result = (int)cmd.ExecuteScalar();
        cmd.Connection.Close();

        if (result > 0)
            return true;
        else
            return false;
    }

    protected void ibEdit_Click(object sender, ImageClickEventArgs e)
    {
        string UID = Request.QueryString["UID"];
        if (IsWriter(UID, User.Identity.Name))
        {
            Response.Redirect("~/ContentEdit.aspx?UID=" + UID);
        }
        else
        {
            lblError.Visible = true;
            lblError.Text = "수정 권한이 없습니다.";
        }
    }

    protected void ibDelete_Click(object sender, ImageClickEventArgs e)
    {
        string UID = Request.QueryString["UID"];

        if (IsWriter(UID, User.Identity.Name))
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SmartMosaicConnectionString"].ConnectionString);
            string sql = "Delete DeepZoomList where UID = @UID";
            SqlCommand cmd = new SqlCommand(sql, con);
            cmd.Parameters.AddWithValue("@UID", UID);

            cmd.Connection.Open();
            cmd.ExecuteNonQuery();
            cmd.Connection.Close();

            Response.Redirect("~/ContentList.aspx");
        }
        else
        {
            lblError.Visible = true;
            lblError.Text = "삭제 권한이 없습니다.";
        }

    }
    protected void Text_Clear()
    {
        tbComment.Text = "";
        Comment.Text = "";

    }

    protected void btn_recom_Click(object sender, ImageClickEventArgs e)
    {
        if (User.Identity.Name.ToString() == null || User.Identity.Name.ToString() == String.Empty || User.Identity.Name.ToString() == "")
        {
            Response.Write("<script>");
            Response.Write("alert('로그인 후 사용하세요!')");
            Response.Write("</script>");
        }
        else
        {
            if (getRecomended() == "1")
            {
                Response.Write("<script>");
                Response.Write("alert('이미 추천하셨습니다!!')");
                Response.Write("</script>");
            }
            else
            {
                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SmartMosaicConnectionString"].ConnectionString);

                string strQuery = "UPDATE DeepZoomList SET Recommend=Recommend+1 WHERE UID=" + HiddenOrder.Value;
                SqlCommand objComm = new SqlCommand(strQuery, con);
                string strQuery2 = "INSERT INTO Recommend (order_id, id) VALUES('" + HiddenOrder.Value + "', '" + User.Identity.Name.ToString() + "')";
                SqlCommand objComm2 = new SqlCommand(strQuery2, con);

                con.Open();
                objComm.ExecuteNonQuery();
                objComm2.ExecuteNonQuery();
                con.Close();


            }
        }
    }
    private string getRecomended()
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SmartMosaicConnectionString"].ConnectionString);

        string strQuery = "SELECT count(*) FROM Recommend WHERE order_id='" + HiddenOrder.Value + "' and User_id='" + User.Identity.Name.ToString() + "'";
        SqlCommand objComm = new SqlCommand(strQuery, con);

        con.Open();
        string strCnt = objComm.ExecuteScalar().ToString();
        con.Close();

        return strCnt;
    }
    private void ListBind()
    {
        string sql = "select idx, User_ID, WriteTime, Comment, order_id from reply where order_id=" + HiddenOrder.Value;
        SqlDataAdapter adapter = new SqlDataAdapter();
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SmartMosaicConnectionString"].ConnectionString);
        adapter.SelectCommand = new SqlCommand(sql,con);
        DataSet ds = new DataSet();
        adapter.Fill(ds);

        this.DataList1.DataSource = ds;
        this.DataList1.DataBind();

    }

    protected void DataList_databound(object sender, DataListItemEventArgs e)
    {
        HtmlGenericControl span = (HtmlGenericControl)e.Item.FindControl("span_content");
        if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            string content = ((DataRowView)e.Item.DataItem)["Comment"].ToString();

            content = Server.HtmlDecode(content);

            content = content.Replace("\r\n", "<br/>");
            Label lbl = new Label();
            lbl.Text = content;
            span.Controls.Add(lbl);
        }

    }
    protected void content_Modify(object sender, EventArgs e)
    {
        if (compareWrite())
        {
            modify_table.Style.Add("display", "none");
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SmartMosaicConnectionString"].ConnectionString);
            string sql = "update reply set Comment = @Comment where idx=@idx";
            SqlCommand cmd = new SqlCommand(sql, con);
            cmd.Parameters.AddWithValue("@Comment", Comment.Text);
            cmd.Parameters.AddWithValue("@no", no);

            cmd.Connection.Open();
            cmd.ExecuteNonQuery();
            cmd.Connection.Close();
        }

        else
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<script language='javascript'>");
            sb.Append("alert('수정할 권한이 없습니다.');");
            sb.Append("</script>");
            Page.RegisterStartupScript("Warning", sb.ToString());
        }




    }
    bool compareWrite()
    {
        string UserName = lblUserName.Text;
        string Writer = lblName.Text;

        if (UserName == Writer)
            return true;
        else
            return false;

    }

    protected void WriteOK_Click(object sender, EventArgs e)
    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SmartMosaicConnectionString"].ConnectionString);
        string sql = "insert into reply(order_id,User_ID,Comment,WriteTime) values (@order_id, @User_ID, @Comment,@WriteTime)";

        SqlCommand cmd = new SqlCommand(sql, con);
        con.Open();

        cmd.Parameters.AddWithValue("@order_id", HiddenOrder.Value);
        cmd.Parameters.AddWithValue("@User_ID",User.Identity.Name);
        cmd.Parameters.AddWithValue("@Comment", tbComment.Text);
        cmd.Parameters.AddWithValue("@WriteTime", DateTime.Now);


        cmd.ExecuteNonQuery();
        con.Close();

        Text_Clear();

        ListBind();
    }
}
